package com.hippo.provider.controller.task;

import cn.hutool.core.date.DateUtil;
import com.hippo.core.constant.Constants;
import com.hippo.core.pojo.po.Tables;
import com.hippo.core.utils.fie.DatFileUtil;
import com.hippo.core.utils.fie.FileUtil;
import com.hippo.database.mapper.TablesMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName BackUpMysqlDataTask
 * @Description TODO 备份mysql数据定时任务
 * @Author tangxl
 * @create 2023-04-28 16:01
 **/
@Component
@Slf4j
@EnableScheduling // 开启定时任务
//@RequiredArgsConstructor
public class BackUpMysqlDataTask {

    @Autowired
    private TablesMapper tablesMapper;

//    @Scheduled(fixedRate = 1000 * 60 * 60 * 24) // 每天执行一次
    public void backUpMysqlData(){
        log.info("开始备份mysql数据");
        backupDatabase(Constants.DATABASE_NAME_ONE);
        backupDatabase(Constants.DATABASE_NAME_TWO);
        log.info("备份mysql数据完成");
    }

    public void backupDatabase(String databaseName){
        // 获取所有表数据
        List<Tables> tables = tablesMapper.selectAllTables(databaseName);
        if(CollectionUtils.isEmpty(tables)){
            return;
        }
        // 创建文件夹
        File file = new File("mysql/"+databaseName);
        if(!file.exists()){
            file.mkdirs();
        }
        // 清空sql文件内容
        FileUtil.writeFile("", "mysql/", databaseName + Constants.FILE_SUFFIX_SQL,false);
        // 循环获取所有表数据，写入文件
        tables.forEach(table -> {
            // 获取表数据
            List<Map<String, Object>> mapData = tablesMapper.findTableDataMap(databaseName+"."+table.getTableName());
            log.info("开始dat文件：{},共{}条数据",table.getTableName()+Constants.FILE_SUFFIX_DAT,mapData.size());
            // 生成dat文件数据
            DatFileUtil.createDatFile(mapData,"mysql/"+databaseName+"/"+table.getTableName()+Constants.FILE_SUFFIX_DAT);
            // 查询创建表sql
            Map<String, Object> tableCreateSql = tablesMapper.findTableCreateSql(databaseName + "." + table.getTableName());
            // 封装sql内容
            StringBuilder content = new StringBuilder("-- Date:").append(DateUtil.formatDate(new Date())).append("\n");
            content.append("DROP table if exists`").append(table.getTableName()).append("`;").append("\n");
            content.append(((HashMap<String,String>)tableCreateSql.get(table.getTableName())).get("Create Table")+";")
                    .append("\n\n");
            boolean b = FileUtil.writeFile(content.toString(), "mysql/", databaseName + Constants.FILE_SUFFIX_SQL,true);
            if(!b){
                log.info("写入sql文件失败：{}",table.getTableName() + Constants.FILE_SUFFIX_SQL);
            }
        });
    }
}
